'use strict'
app.controller('ProjectInfoController', function($scope, $state, $http, $timeout, time, obj, $stateParams) {

    let idStr = $stateParams.id;
    let index = idStr.indexOf("_");
    let id = 0;
    $scope.tabType = 1;
    if(index > -1){
        let arr = idStr.split("_");
        id = arr[0];
        $scope.tabType = arr[1];
    }else{
        id = $stateParams.id;
    }

    $scope.datasourceApi = $scope.serverUrl + "web/datasource";

    $scope.project = {

    }

    $scope.form = {
        "isAdd": true, //true表示新增，false表示修改
        "title": '新增',
        "entity": {
            "id": '',
            "name": '',
            "account": '',
            "password": '',
            "url": '',
            "driver": '',
            "projectId": id
        }
    };

    $scope.query = {
        "size": 10,
        "page": 1,
        "name": "",
        "type": 1,
        "projectId": id
    };

    $scope.datasourceTotal = 0;
    $scope.templateTotal = 0;

    let tbl;
    let tbl2;
    let layer = layui.layer

    $timeout(function(){
        $http.get($scope.serverUrl + "web/project/" + id).then(function(res){
            if(res.data.code === 1){
                $scope.project = res.data.data;
            }else{
                layer.msg(res.data.msg, {icon: 5});
            }
        },
        function(err){
            layer.msg('接口请求异常', {icon: 5});
        });


        tbl = $('#tbl').DataTable({
            "ajax" : function (data, callback, settings) {
                //封装请求参数
                $scope.query.size = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
                $scope.query.page = (data.start / data.length)+1;//当前页码
                Object.keys($scope.query).forEach(function(key) {
                    let val = $scope.query[key]
                    if(val === ""){
                        $scope.query[key] = undefined;
                    }
                });
                let returnData = {};
                returnData.recordsTotal = 0;//返回数据全部记录
                returnData.recordsFiltered = 0;//后台不实现过滤功能，每次查询均视作全部结果
                returnData.data = [];//返回的数据列表
                $http.post($scope.serverUrl + 'web/projectToDatasource/page/list', $scope.query).then(function(res){
                        // console.log(res.data);
                        let data = res.data;
                        if(data.code === 1){
                            $scope.datasourceTotal = data.data.total;
                            returnData.recordsTotal = data.data.total;//返回数据全部记录
                            returnData.recordsFiltered = data.data.total;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = data.data.records;//返回的数据列表
                        }
                        callback(returnData);
                    },
                    function(err){
                        alert("数据加载请求异常");
                    });
            },
            "serverSide":true,
            "language":$scope.datatables_lang, //提示信息
            "renderer": "bootstrap", //渲染样式：Bootstrap和jquery-ui
            "pagingType": "full_numbers", //分页样式：simple,simple_numbers,full,full_numbers
            "bFilter": true,
            "bSort": false,
            /*"scrollX": true,*/
            "fnInitComplete":function (oSettings, json) {

            },
            "columns": [
                {
                    "targets": 0,
                    "render": function(data, type, row){
                        return '<label class="i-checks m-b-none"><input type="checkbox"><i></i></label>';
                    }
                },
                {"data": "name"},
                {"data": "account"},
                {"data": "driver"},
                // {"data": "url"},
                {
                    "render": function(data, type, row){
                        return time.format(row.createTime);
                    }
                },
                {
                    "render": function(data, type, row){
                        let html = '<span class="btn btn-info btn-sm" name="edit">编辑</span>';
                        html += '<span class="btn btn-danger btn-sm" style="margin-left:3px;" name="del">删除</span>';
                        return html;
                    }
                },
            ]
        });

        $('#tbl tbody').on('click', 'span[name="edit"]', function(e){
            let entity = tbl.row($(e.target).parents("tr")).data();
            // console.log(entity);
            $scope.form.isAdd = false;
            $scope.form.title = '修改';
            obj.copy(entity, $scope.form.entity);
            $scope.$apply();
            $("#add").modal("show");
        });

        $('#tbl tbody').on('click', 'span[name="del"]', function(e){
            let entity = tbl.row($(e.target).parents("tr")).data();
            let data = {
                datasourceId: entity.id,
                projectId: id
            }
            // console.log(data)
            $http({
                method: 'DELETE',
                url: $scope.serverUrl + 'web/projectToDatasource/',
                data: data,
                headers: {
                    'Content-type': 'application/json;charset=utf-8'
                }
            }).then(function(res) {
                tbl.ajax.reload();
            }, function(err) {
                toaster.pop('info', "title", "请求异常");
            });
        });

        tbl2 = $('#tbl2').DataTable({
            "ajax" : function (data, callback, settings) {
                //封装请求参数
                $scope.query.size = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
                $scope.query.page = (data.start / data.length)+1;//当前页码
                Object.keys($scope.query).forEach(function(key) {
                    let val = $scope.query[key]
                    if(val === ""){
                        $scope.query[key] = undefined;
                    }
                });
                let returnData = {};
                returnData.recordsTotal = 0;//返回数据全部记录
                returnData.recordsFiltered = 0;//后台不实现过滤功能，每次查询均视作全部结果
                returnData.data = [];//返回的数据列表
                $http.post($scope.serverUrl + 'web/projectToTemplate/page/list', $scope.query).then(function(res){
                        // console.log(res.data);
                        let data = res.data;
                        if(data.code === 1){
                            $scope.templateTotal = data.data.total;
                            returnData.recordsTotal = data.data.total;//返回数据全部记录
                            returnData.recordsFiltered = data.data.total;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = data.data.records;//返回的数据列表
                        }
                        callback(returnData);
                    },
                    function(err){
                        layer.msg('接口请求异常', {icon: 5});
                    });
            },
            "serverSide":true,
            "language":$scope.datatables_lang, //提示信息
            "renderer": "bootstrap", //渲染样式：Bootstrap和jquery-ui
            "pagingType": "full_numbers", //分页样式：simple,simple_numbers,full,full_numbers
            "bFilter": true,
            "bSort": false,
            /*"scrollX": true,*/
            "fnInitComplete":function (oSettings, json) {

            },
            "columns": [
                {
                    "targets": 0,
                    "render": function(data, type, row){
                        return '<label class="i-checks m-b-none"><input type="checkbox"><i></i></label>';
                    }
                },
                {
                    "render": function(data, type, row){
                        return row.name;
                    }
                },
                {
                    "render": function(data, type, row){
                        return row.tplType;
                    }
                },
                {
                    "render": function(data, type, row){
                        return row.fileType;
                    }
                },
                {
                    "render": function(data, type, row){
                        return time.format(row.createTime);
                    }
                },
                {
                    "render": function(data, type, row){
                        let html = '<span class="btn btn-info btn-sm" name="edit">修改</span>';
                        html += '<span class="btn btn-danger btn-sm" style="margin-left:3px;" name="del">删除</span>';
                        html += '<span class="btn btn-default btn-sm" style="margin-left:3px;" name="preview">预览</span>';
                        return html;
                    }
                },
            ]
        });

        $('#tbl2 tbody').on('click', 'span[name="edit"]', function(e){
            let entity = tbl2.row($(e.target).parents("tr")).data();
            // console.log(entity)
            $state.go("app.templateForm", {id: entity.id + "_" + id});
        });

        $('#tbl2 tbody').on('click', 'span[name="del"]', function(e){
            let entity = tbl2.row($(e.target).parents("tr")).data();
            let data = {
                templateId: entity.id,
                projectId: id
            }
            $http({
                method: 'DELETE',
                url: $scope.serverUrl + 'web/projectToTemplate/',
                data: data,
                headers: {
                    'Content-type': 'application/json;charset=utf-8'
                }
            }).then(function(res) {
                tbl2.ajax.reload();
            }, function(err) {
                toaster.pop('info', "title", "请求异常");
            });
        });

        $('#tbl2 tbody').on('click', 'span[name="preview"]', function(e){
            let entity = tbl2.row($(e.target).parents("tr")).data();
            $http.get($scope.serverUrl + "web/template/test/" + entity.id).then(function(res){
                if(res.data.code === 1){
                    window.open($scope.serverUrl + "web/template/preview/" + res.data.data, "_blank");
                    // download($scope.api + "/down/" + res.data.data, res.data.data);
                }else{
                    layer.msg(res.data.msg, {icon: 5});
                }
            },
            function(err){
                layer.msg('接口请求异常', {icon: 5});
            });
        });



    }, 0);

    $scope.add = function(){
        $scope.form.isAdd = true;
        $scope.form.title = '新增';
        $scope.form = {
            "isAdd": true, //true表示新增，false表示修改
            "title": '新增',
            "entity": {
                "id": '',
                "name": '',
                "account": '',
                "password": '',
                "type": 1,
                "url": '',
                "driver": '',
                "projectId": id
            }
        };
        $("#add").modal("show");
    };

    $scope.add2 = function(){
        $state.go("app.templateForm", {id: "0_" + id});
    };

    $scope.save = function(){
        let url =  $scope.datasourceApi + "/";
        if($scope.form.isAdd){
            $http.post(url, $scope.form.entity).then(function(res){
                tbl.ajax.reload();
                $("#add").modal("hide");
            },
            function(err){

            });
        }else{
            $http.post(url, $scope.form.entity).then(function(res){
                tbl.ajax.reload();
                $("#add").modal("hide");
            },
            function(err){

            });
        }
    }

    $scope.test = function(){
        let url =  $scope.datasourceApi + "/test";
        $http.post(url, $scope.form.entity).then(function(res){
            if(res.data.code === 1){
                layer.msg('连接成功', {icon: 1});
            }else{
                layer.msg('连接失败，原因:' + res.data.msg, {icon: 1});
            }
        },
        function(err){

        });
    }

    $scope.code = function (){
        if($scope.datasourceTotal === 0){
            layer.msg('请添加数据源', {icon: 1});
            return;
        }
        if($scope.templateTotal === 0){
            layer.msg('请添加模板', {icon: 1});
            return;
        }
        $state.go("app.code", {id: id});
    }
});